<template>
  <div class="container" ref="container"></div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import * as THREE from "three";
import { OrbitControls } from "three/addons/controls/OrbitControls.js";

const container = ref();

// Our Javascript will go here.
// 创建场景
const scene = new THREE.Scene();
// 改变场景的背景-颜色
scene.background = new THREE.Color(0x666666);

// 创建相机
const camera = new THREE.PerspectiveCamera(
  75,
  window.innerWidth / window.innerHeight,
  0.1,
  1000
);
// 调整相机位置
camera.position.z = 10;
camera.position.y = 3;

// 创建平面几何体
// const geometry = new THREE.PlaneGeometry(1, 1);
// const material = new THREE.MeshBasicMaterial({
//   color: 0xffff00,
//   side: THREE.DoubleSide,
//   wireframe:true
// });
// const plane = new THREE.Mesh(geometry, material);
// scene.add(plane);

const geometry = new THREE.BufferGeometry();
// 创建一个简单的矩形. 在这里我们左上和右下顶点被复制了两次。
// 因为在两个三角面片里，这两个顶点都需要被用到。
const vertices = new Float32Array([
  -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0,

  // 1.0, 1.0, 1.0,
  -1.0, 1.0, 1.0,
  // -1.0, -1.0, 1.0,
]);
// itemSize = 3 因为每个顶点都是一个三元组。
geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));

// 确认几何体的顶点
// 利用索引来确认几何体的绘制方式
const indexs = new Uint16Array([0, 1, 2, 2, 3, 0]);

geometry.index = new THREE.BufferAttribute(indexs, 1);

const material = new THREE.MeshBasicMaterial({
  color: 0x42d12a,
  side: THREE.DoubleSide,
  wireframe: true,
});
const mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);

// 创建渲染器
const renderer = new THREE.WebGLRenderer();
// 调整渲染器窗口大小
renderer.setSize(window.innerWidth, window.innerHeight);

// 添加一个网格地面
const gridHepler = new THREE.GridHelper(10, 10);
scene.add(gridHepler);

// 在页面中添加元素
onMounted(() => {
  // 将渲染节点添加到页面
  container.value.appendChild(renderer.domElement);
});

// 添加轨道控制器
const controls = new OrbitControls(camera, renderer.domElement);

// 开启阻尼效果 （视角拖动的时候会有惯性）
controls.enableDamping = true; // 开启
controls.dampingFactor = 0.05; // 阻尼惯性大小

// 开启相机自动旋转
// controls.autoRotate = true;
// controls.autoRotateSpeed = 3;

// 添加坐标轴
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

// 让立方体动起来
function animate() {
  requestAnimationFrame(animate);
  // 轨道控制器更新
  controls.update();
  // 调用渲染器进行渲染
  renderer.render(scene, camera);
}

animate();
</script>

<style>
* {
  margin: 0;
}
html,
body {
  width: 100vw;
  height: 100vh;
}

.container {
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

.buttons {
  left: 20px;
  position: fixed;
  top: 20px;
}

#gui {
  position: absolute;
  right: 0;
  width: 300px;
}
</style>
